package com.buho29.rcmanager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;

import com.buho29.rcmanager.bd.DatabaseAdapter;
import com.buho29.rcmanager.bd.TableModel;
import com.buho29.rcmanager.utils.BitmapUtils;
import com.buho29.rcmanager.utils.Make;

public class ModelEdit extends Activity {

    private static final int ACTIVITY_TAKE_PICTURE=0; 
    private static final int ACTIVITY_DRIVE=1;
    
	private EditText mNameText;
    private EditText mDescriptionText;
    private Spinner mPowerType;
    private ImageButton mImage;
    
    public static final String CMD="cmd";
    
	private DatabaseAdapter mDbAdapter;
	private TableModel mDbTableModel = new TableModel();

	private String mImg;
	private Long mId;
	private int mCmd;

	private int mWidthImg;
	private int mHeighImg;
	   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, Menu.FIRST,0, getString(R.string.alarm));
        menu.add(0, Menu.FIRST+1,0, getString(R.string.damage));
        menu.add(0, Menu.FIRST+2,0, getString(R.string.power));
        return true;
    }    
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case Menu.FIRST:
        	Intent i = new Intent(this, AlarmView.class);
	        i.putExtra(TableModel.COL_ROW_ID, mId);
	        i.putExtra(PowersView.CMD, PowersView.CMD_MODEL);
	        startActivityForResult(i, ACTIVITY_DRIVE);
            return true;
        case Menu.FIRST+1:
        	i = new Intent(this, DamageView.class);
	        i.putExtra(TableModel.COL_ROW_ID, mId);
	        i.putExtra(PowersView.CMD, PowersView.CMD_MODEL);
	        startActivityForResult(i, ACTIVITY_DRIVE+1);
            return true;
        case Menu.FIRST+2:
        	i = new Intent(this, PowersView.class);
	        i.putExtra(TableModel.COL_ROW_ID, mId);
	        i.putExtra(PowersView.CMD, PowersView.CMD_MODEL);
	        startActivityForResult(i, ACTIVITY_DRIVE+2);
            return true;
	    }        
        return super.onMenuItemSelected(featureId, item);
    }
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.model_edit);
        
        final float scale = getResources().getDisplayMetrics().density;
        mWidthImg = (int) (240 * scale);
        mHeighImg = (int) (160 * scale);
        
        mNameText = (EditText) findViewById(R.id.tvName);
        mDescriptionText = (EditText) findViewById(R.id.tvDescription);
        mPowerType = (Spinner) findViewById(R.id.spPowerType);
        mImage = (ImageButton) findViewById(R.id.ibImage);
        Button confirmButton = (Button) findViewById(R.id.btSave);
      
        mDbAdapter = DatabaseAdapter.getInstance(this); 
        
        Bundle extras = getIntent().getExtras(); 
        if(savedInstanceState != null){
			mId =  savedInstanceState.getLong(TableModel.COL_ROW_ID);
        	mImg = savedInstanceState.getString(TableModel.COL_IMAGE);
			mCmd = savedInstanceState.getInt(CMD);
		} else if(extras != null) {           
			mId =  extras.getLong(TableModel.COL_ROW_ID);
			mCmd = extras.getInt(CMD);
			
		}

        mDbTableModel.setSQLiteDatabase(mDbAdapter.getDatabase());
        mDbTableModel.setId(mId);
		populateFields();
		
		if(mImg != null) setImage(mImg);
       
        confirmButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                saveData();
            }
            
        });
        
        mImage.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	Intent activityIntent = new Intent();
	    		activityIntent.setAction("android.intent.action.GET_CONTENT");
	    		activityIntent.setType("image/*");
	    		startActivityForResult(activityIntent, ACTIVITY_TAKE_PICTURE);
            }
            
        });
    }    

    
    private void populateFields() {
        	
        if(mCmd == TableModel.CMD_EDIT){
        	mDbTableModel.load();
        		
        	String name = mDbTableModel.getName();
        	mNameText.setText(name);
        	mDescriptionText.setText(mDbTableModel.getDescription());
        	

        	setImage(mDbTableModel.getImage());
        	
        	int index = mDbTableModel.getPower_type();
        	if(index>0) mPowerType.setSelection(index);
        	else mPowerType.setSelection(0);
        		
        	setTitle(name);
        } else setTitle(getText(R.string.New));
        	
    }
    
    private void saveData() {
        String name = mNameText.getText().toString();
        String description = mDescriptionText.getText().toString();
        
        int index = mPowerType.getSelectedItemPosition();
        
        mDbTableModel.setName(name);
        mDbTableModel.setDescription(description);
        mDbTableModel.setPower_type(index);
        
        String path = mDbTableModel.getImage();
    	if(path != null && mImg != null && path != mImg ){
    		deleteImage(path);
    	}
    	
    	if(mImg != null && path != mImg ){
    		mDbTableModel.setImage(mImg);
    	}
    		
        mDbTableModel.save();
        
        if (mCmd == TableModel.CMD_EDIT) {
            Make.toast(this,getText(
    			R.string.saved)).show();
        } else {
            Make.toast(this,getText(
    			R.string.created)).show();
        }
        
        
        setResult(RESULT_OK);
        finish();
    }
        
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        
        switch(requestCode) {
	        case ACTIVITY_TAKE_PICTURE :
	        	if(resultCode == RESULT_OK){
	        		
	        		if( 
	        			mImg != null && 
	        			//mDbTableModel.getImage()!=null &&
	        			mImg != mDbTableModel.getImage()
	        		){
	        			
	        			deleteImage(mImg);
	        		}
	        		//mImg 
	        		Uri uri = intent.getData();
	        		
	        		Bitmap img = null;
	        		Bitmap img2 = null;
	        		 try {
	        			 
		    			File file = getDir("picture", MODE_APPEND);
		    			mImg = file.getPath()+"/" +new Date().getTime()+ ".jpg";
		    		

						Options options = new Options();
						
		    			FileOutputStream out = new FileOutputStream(mImg);
						
		    			InputStream source = getContentResolver().openInputStream(uri);
		    			
						
						options.inJustDecodeBounds = true;
						BitmapFactory.decodeStream(source, null, options);
						
						int scaleFactor = BitmapUtils.resolveSampleSize(options,mWidthImg);
						
						options.inJustDecodeBounds = false;
					    options.inSampleSize = scaleFactor ;
					    
						source = getContentResolver().openInputStream(uri);
						img = BitmapFactory.decodeStream(source, null, options);
		    			
						if(img.getWidth()==img.getHeight()){
							img = BitmapUtils.rotateBitmap(img);
						}
						
						img2 = BitmapUtils.scaleBitmap(img,mWidthImg,mHeighImg);
						
						img2.compress(CompressFormat.JPEG, 100, out);
		    		
		    			out.flush();
		    			out.close();
		    			
		    			img2.recycle();
		    			
					} catch (Exception e) {
						Log.w("ModelEdit", e.toString());
						Make.toast(this,"ModelEdit :" + e.toString()).show();
					}
	        		
	        		setImage(mImg);
	        	}
	        	break;
        }
    }

    private void setImage(String path){
    	if(path != null){
	    	File file = new File(path);
	    	if(file.isFile()){
	    		Uri uri = Uri.parse(path);
	    		mImage.setImageURI(uri);
	    	}else {
	    		mImage.setImageResource(R.drawable.no_found_image);
	    	}	
    	}
    }
    
    private void deleteImage(String path){
    	File img = new File(path);
    	if(img.exists()) img.delete();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        
        outState.putLong(TableModel.COL_ROW_ID, mId);
        outState.putString(TableModel.COL_IMAGE, mImg);
        	
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	if(mImg !=null && mDbTableModel.getImage()!= mImg){
        		deleteImage(mImg);
        	}
            return super.onKeyDown(keyCode, event);
        }
        return false;
    }
    
    
}
